package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.article.ArticleConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    GeneratePageService generatePageService;
    @Autowired
    RabbitTemplate rabbitTemplate;


    @Transactional
    @Override
    public void publishArticle(Integer newsId) {
        // 1. 查询并校验文章
        WmNews wmNews = getWmNews(newsId);
        // 2. 将wmNews封装成apArticle
        ApArticle article = getApArticle(wmNews);
        // 3. 保存或修改aparticle
        saveOrUpdateArticle(article);
        // 4. 保存 关联配置信息  和  文章内容
        saveConfigAndContent(article,wmNews);
        // 5.  页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),article);
        // 6. 更新wmNews的状态为9
        updateWmNews(wmNews,article);
        // 7. 通知es索引库添加文章
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,article.getId());
        log.info("文章发布成功，并发送索引库更新通知   文章id: {}",article.getId());
    }

    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        // 1. 校验参数  size   type   时间   频道
        if (dto.getSize() == null || dto.getSize() < 1) {
            dto.setSize(10);
        }
        if(!ArticleConstants.LOADTYPE_LOAD_MORE.equals(loadtype)&&!ArticleConstants.LOADTYPE_LOAD_NEW.equals(loadtype)){
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE; // 默认查询更多
        }
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        if(StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 2.调用articleMapper
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
        // 将文章静态页路径  加 前缀
        for (ApArticle apArticle : apArticles) {
            apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
        }
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult load2(Short loadtypeLoadMore, ArticleHomeDTO dto, boolean firstPage) {
        if (firstPage){
            String hotArticleJson = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(hotArticleJson)){
                List<ApArticle> apArticles = JSON.parseArray(hotArticleJson, ApArticle.class);
                for (ApArticle apArticle : apArticles) {
                    apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
                }
                ResponseResult responseResult = ResponseResult.okResult(apArticles);
                responseResult.setHost(webSite);
                return responseResult;
            }
        }
        return load(loadtypeLoadMore,dto);
    }

    private void updateWmNews(WmNews wmNews, ApArticle article) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode()); // 状态改为9 发布状态
        wmNews.setArticleId(article.getId());
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (!responseResult.checkCode()) {
            log.error("远程调用修改文章方法失败  文章id:{} ",article.getId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用修改文章方法失败");
        }
    }

    private void saveConfigAndContent(ApArticle article, WmNews wmNews) {
        // 1. 保存配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(article.getId());
        config.setIsComment(true); // 是否可以评论
        config.setIsForward(true); // 是否可以转发
        config.setIsDown(false);// 是否下架
        config.setIsDelete(false); // 是否被删除
        apArticleConfigMapper.insert(config);
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(article.getId());
        content.setContent(wmNews.getContent()); // 内容
        apArticleContentMapper.insert(content);
    }


    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    private void saveOrUpdateArticle(ApArticle article) {
        // 判断文章的id是否存在
        if(article.getId() == null){
            // 如果不存在就保存   (点赞量  阅读量 收藏量  评论量)
            article.setCollection(0);//收藏量
            article.setLikes(0);// 点赞量
            article.setViews(0);//阅读量
            article.setComment(0); // 评论量
            save(article);
        }else {
            // 存在  修改article文章数据
            ApArticle oldArticle = getById(article.getId());
            if(oldArticle == null){
                log.error("之前关联的文章数据不存在  文章id:{} ",oldArticle.getId());
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"之前关联的文章数据不存在");
            }
            updateById(article);
            // 删除之前关联的配置信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,article.getId()));
            // 删除之前关联的内容信息
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,article.getId()));
        }
    }

    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    AdminFeign adminFeign;

    private ApArticle getApArticle(WmNews wmNews) {
        // 1. 创建article对象，将wmNews中的属性拷贝到article中
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(wmNews,article);
        // 2. 补全未拷贝属性  (articleId flag  layout)
        article.setId(wmNews.getArticleId());
        article.setFlag((byte)0);
        article.setLayout(wmNews.getType());// 布局类型
        // 3. 补全作者信息
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if(apAuthor==null){ // 补全作者信息
            log.error("查询作者信息失败  文章id:{}  自媒体用户id:{}",wmNews.getId(),wmNews.getUserId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"作者信息不存在");
        }
        article.setAuthorId(Long.valueOf(apAuthor.getId()));
        article.setAuthorName(apAuthor.getName());
        // 4. 频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            log.error("远程调用查询频道信息失败  频道id:{}",wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用查询频道信息失败");
        }
        AdChannel channel = channelResult.getData();
        if (channel==null) {
            log.error("为查询到相关频道信息  频道id:{}",wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"为查询到相关频道信息");
        }
        article.setChannelName(channel.getName());
        return article;
    }


    @Autowired
    WemediaFeign wemediaFeign;
    /**
     * 远程查询自媒体文章信息  并校验
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        // 1. 使用feign查询自媒体文章
        ResponseResult<WmNews> newsResult = wemediaFeign.findWmNewsById(newsId);
        if (!newsResult.checkCode()) {
            log.error("远程查询自媒体文章信息失败  文章id:{}",newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程查询自媒体文章信息失败");
        }
        // 2. 校验文章是否存在
        WmNews wmNews = newsResult.getData();
        if (wmNews == null) {
            log.error("未查询到自媒体文章数据  文章id:{}",newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到自媒体文章数据");
        }
        // 3. 校验文章状态  是否为 4  8
        short status = wmNews.getStatus().shortValue(); // 文章状态

        if(WmNews.Status.ADMIN_SUCCESS.getCode()!=status&&WmNews.Status.SUCCESS.getCode()!=status){
            log.error("文章的状态不是审核通过状态，发布文章失败  文章id:{}",newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章的状态不是审核通过状态，发布文章失败");
        }
        return wmNews;
    }
}